package chapter04.part02;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 实现一个简单的服务器
 * 
 * 1. 创建服务器端口
 * 2. 等待连接
 * 3. 接收命令
 * 4. 处理
 * 5. 返回数据
 * 
 * @author insight
 * @since 2021/8/29
 */
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        start();
    }

    private static void start() throws IOException {
        // 创建端口
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("ServerSocket Created Successfully...");
            // 监听端口 会阻塞
            try (Socket incoming = serverSocket.accept()) {
                System.out.println("Successfully Connected to ServerSocket...");
                // 接收 & 返回数据
                try (Scanner in = new Scanner(incoming.getInputStream(),
                        StandardCharsets.UTF_8);
                     PrintWriter out = new PrintWriter(
                             new OutputStreamWriter(incoming.getOutputStream(), StandardCharsets.UTF_8), true)) {
                    out.println("Hello, Here is insight's ServerDemo!");

                    boolean online = true;
                    while (online && in.hasNextLine()) {
                        String command = in.nextLine();
                        String content = "Echo: " + command;
                        System.out.println(content);
                        out.println(content);
                        if ("exit".equals(command.trim().toLowerCase())) {
                            online = false;
                            out.println("GoodBye");
                        }
                    }

                    System.out.println("Disconnect From ServerSocket...");
                }
            }
        }
    }
}